package com.baomidou.springboot.hystrix;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.springboot.entity.User;
import com.baomidou.springboot.util.RedisUtil;
import com.baomidou.springboot.util.SpringUtils;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;


public class GetShopInfoFromReidsCacheCommand extends HystrixCommand<User> {
	
	private Long shopId;
	
	public GetShopInfoFromReidsCacheCommand(Long shopId) {
		super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RedisGroup"))
				.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
						.withExecutionTimeoutInMilliseconds(100)
						.withCircuitBreakerRequestVolumeThreshold(1000)
						.withCircuitBreakerErrorThresholdPercentage(70)
						.withCircuitBreakerSleepWindowInMilliseconds(60 * 1000))
				);  
		this.shopId = shopId;
	}
	
	@Override
	protected User run() throws Exception {
		RedisUtil redisUtil = (RedisUtil) SpringUtils
				.getBean("redisUtil");
		String key = "shop_info_" + shopId;
		String user =  redisUtil.get(key,0);
		if(user != null) {
			return JSONObject.parseObject(user, User.class);
		}
		return null;
	} 
	
	@Override
	protected User getFallback() {
		return null;
	}

}